package com.kele.controller.AliPayController;

import com.kele.dao.UserDao;
import com.kele.domain.Order;
import com.kele.domain.User;
import com.kele.pay.Alipay;
import com.kele.service.OrderService;
import com.kele.service.UserService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author 赵奥林
 * @date 2021年06月11日 22:21
 * @Description 支付控制器
 */
@Controller
@RequestMapping("/pay")
public class AliPayController {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    /**
     * 生成支付宝支付页面
     *
     * @param sn
     * @param model
     * @return
     * @description (order_id订单编号，order_amount订单金额，order_name订单名称，order_body订单描述)
     */
    @RequestMapping("/toAlipay")
    public String toAlipay(@RequestParam(name = "sn", required = true) String sn,
                           Model model) {
        Order order = orderService.queryOrderById(sn);
        String html = Alipay.generatePCPayHtml(order.getOrder_id(),
                order.getOrder_amount(),
                order.getOrder_name(),
                order.getOrder_body());
        model.addAttribute("html", html);
        return "static_resources/jsp/alipay_pc";
    }


    /**
     * 支付宝支付的异步通知接口
     * @return
     */
    @RequestMapping("/alipay_notify")
    @ResponseBody
    public String alipay(HttpServletRequest request) {
        //检查异步通知的签名是否合法
        if (!Alipay.isValid(request)){
            return "false";
        }
        //表示签命验证成功
        //订单号
        String sn = request.getParameter("out_trade_no");
        //支付宝交易号
        String paySn=request.getParameter("trade_no");
        //支付金额
        String totalAmount=request.getParameter("total_amount");
        //支付状态
        String status=request.getParameter("trade_status");

        Order order = orderService.queryOrderById(sn);
        if (order==null){
            return "false";
        }
        if (order.getOrder_amount().compareTo(new BigDecimal(totalAmount)) != 0) {
            return "false";
        }
        //支付宝交易号
        order.setOrder_payid(paySn);
        if (status.equals("TRADE_SUCCESS")) {
            //支付状态为已支付
            order.setOrder_status(Order.pay_status_paid);
        } else {
            order.setOrder_status(Order.pay_status_failed);
        }

        //支付时间,utilDate转化成sqlDate
        Date utilDate = new Date();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
        order.setPaid_time(sqlDate);

        orderService.updateOrderState(order);

        return "true";
    }


}
